<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商户ID" prop="storeId">
        <el-input
          v-model="queryParams.storeId"
          placeholder="请输入商户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="省份" prop="province">
        <el-input
          v-model="queryParams.province"
          placeholder="请输入省份"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input
          v-model="queryParams.city"
          placeholder="请输入城市"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区/县" prop="district">
        <el-input
          v-model="queryParams.district"
          placeholder="请输入区/县"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入详细地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入门店电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['core:storeDetail:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['core:storeDetail:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['core:storeDetail:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['core:storeDetail:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeDetailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" width="80" />
      <el-table-column label="商户ID" align="center" prop="storeId" width="80" />
      <el-table-column label="省份" align="center" prop="province" width="100" />
      <el-table-column label="城市" align="center" prop="city" width="100" />
      <el-table-column label="区/县" align="center" prop="district" width="100" />
      <el-table-column label="详细地址" align="center" prop="address" width="200" show-overflow-tooltip />
      <el-table-column label="门店电话" align="center" prop="phone" width="120" />
      <el-table-column label="资质信息说明" align="center" prop="qualificationInfo" width="150" show-overflow-tooltip>
        <template #default="scope">
          <div class="text-content">{{ scope.row.qualificationInfo || '-' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="营业执照" align="center" prop="businessLicenseUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.businessLicenseUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商户介绍说明" align="center" prop="description" width="150" show-overflow-tooltip>
        <template #default="scope">
          <div class="text-content">{{ scope.row.description || '-' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="营业状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ statusMap[scope.row.status] || '未知' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleViewDetail(scope.row)">查看详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['core:storeDetail:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['core:storeDetail:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商户详情信息对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="storeDetailRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商户ID" prop="storeId">
              <el-input v-model="form.storeId" placeholder="请输入商户ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入门店电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="省份" prop="province">
              <el-input v-model="form.province" placeholder="请输入省份" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="城市" prop="city">
              <el-input v-model="form.city" placeholder="请输入城市" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区/县" prop="district">
              <el-input v-model="form.district" placeholder="请输入区/县" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 省市区级联选择器 -->
        <el-form-item label="所在地区" prop="regionIds">
          <el-cascader
            v-model="form.regionIds"
            :options="regionOptions"
            :props="cascaderProps"
            placeholder="请选择省市区"
            style="width: 100%"
            clearable
            @change="handleRegionChange"
          />
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="资质信息说明" prop="qualificationInfo">
          <el-input 
            v-model="form.qualificationInfo" 
            type="textarea" 
            :rows="3"
            placeholder="请输入资质信息说明" 
          />
        </el-form-item>

        <el-form-item label="营业执照" prop="businessLicenseUrl">
          <image-upload v-model="form.businessLicenseUrl"/>
        </el-form-item>

        <el-form-item label="商户介绍说明" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入商户介绍说明" 
          />
        </el-form-item>

        <el-form-item label="营业状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择营业状态" style="width: 100%">
            <el-option v-for="(label, value) in statusMap" :key="value" :label="label" :value="parseInt(value)" />
          </el-select>
        </el-form-item>

        <el-form-item label="逻辑删除标志" prop="delFlag" v-if="false">
          <el-input v-model="form.delFlag" placeholder="请输入逻辑删除标志" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情信息弹窗 -->
    <el-dialog 
      v-model="detailDialog" 
      title="商户详情信息" 
      width="800px" 
      append-to-body
      :before-close="handleDetailClose"
    >
      <div v-if="detailData" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商户ID">{{ detailData.storeId }}</el-descriptions-item>
          <el-descriptions-item label="门店电话">{{ detailData.phone }}</el-descriptions-item>
          <el-descriptions-item label="省份">{{ detailData.province }}</el-descriptions-item>
          <el-descriptions-item label="城市">{{ detailData.city }}</el-descriptions-item>
          <el-descriptions-item label="区/县">{{ detailData.district }}</el-descriptions-item>
          <el-descriptions-item label="营业状态">
            <el-tag :type="detailData.status === 1 ? 'success' : 'danger'">
              {{ statusMap[detailData.status] }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="详细地址" :span="2">{{ detailData.address }}</el-descriptions-item>
          <el-descriptions-item label="经度">{{ detailData.longitude }}</el-descriptions-item>
          <el-descriptions-item label="纬度">{{ detailData.latitude }}</el-descriptions-item>
          <el-descriptions-item label="资质信息说明" :span="2">
            <div class="detail-text">{{ detailData.qualificationInfo || '暂无' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="商户介绍说明" :span="2">
            <div class="detail-text">{{ detailData.description || '暂无' }}</div>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="license-section" v-if="detailData.businessLicenseUrl">
          <div class="section-title">营业执照</div>
          <image-preview :src="detailData.businessLicenseUrl" :width="300" :height="200"/>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="StoreDetail">
import { listStoreDetail, getStoreDetail, delStoreDetail, addStoreDetail, updateStoreDetail } from "@/api/core/storeDetail"
import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
import { transformData, getRegionNames, getRegionIds } from "@/utils/region"

const { proxy } = getCurrentInstance()

// 省市区级联选择器配置
const regionOptions = ref(transformData())
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: false,
  emitPath: true
}

// 状态映射
const statusMap = { 0: '关闭', 1: '营业' }

const storeDetailList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 详情弹窗相关
const detailDialog = ref(false)
const detailData = ref(null)

// 省市区选择器变化处理
function handleRegionChange(value) {
  if (value && value.length >= 3) {
    const [provinceId, cityId, districtId] = value
    const regionNames = getRegionNames(provinceId, cityId, districtId)
    
    // 更新表单中的省市区名称字段
    form.value.province = regionNames.province
    form.value.city = regionNames.city
    form.value.district = regionNames.district
  } else {
    // 清空省市区名称
    form.value.province = ''
    form.value.city = ''
    form.value.district = ''
  }
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storeId: null,
    province: null,
    city: null,
    district: null,
    address: null,
    phone: null,
    qualificationInfo: null,
    businessLicenseUrl: null,
    description: null,
    status: null,
  },
  rules: {
    storeId: [
      { required: true, message: "商户ID不能为空", trigger: "blur" }
    ],
    regionIds: [
      { required: true, message: "请选择所在地区", trigger: "change" }
    ],
    province: [
      { required: true, message: "省份不能为空", trigger: "blur" }
    ],
    city: [
      { required: true, message: "城市不能为空", trigger: "blur" }
    ],
    district: [
      { required: true, message: "区/县不能为空", trigger: "blur" }
    ],
    address: [
      { required: true, message: "详细地址不能为空", trigger: "blur" }
    ],
    longitude: [
      { required: true, message: "经度不能为空", trigger: "blur" }
    ],
    latitude: [
      { required: true, message: "纬度不能为空", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "门店电话不能为空", trigger: "blur" }
    ],
    businessLicenseUrl: [
      { required: true, message: "营业执照图片地址不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "营业状态不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// 查看详情
function handleViewDetail(row) {
  detailData.value = row
  detailDialog.value = true
}

// 关闭详情弹窗
function handleDetailClose() {
  detailDialog.value = false
  detailData.value = null
}

/** 查询商户详情信息列表 */
function getList() {
  loading.value = true
  listStoreDetail(queryParams.value).then(response => {
    storeDetailList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    storeId: null,
    regionIds: [], // 省市区ID数组
    province: null,
    city: null,
    district: null,
    address: null,
    longitude: null,
    latitude: null,
    phone: null,
    qualificationInfo: null,
    businessLicenseUrl: null,
    description: null,
    status: 1,
    delFlag: 0,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("storeDetailRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商户详情信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getStoreDetail(_id).then(response => {
    form.value = response.data
    
    // 处理省市区的回显
    if (form.value.province && form.value.city && form.value.district) {
      const regionIds = getRegionIds(form.value.province, form.value.city, form.value.district)
      form.value.regionIds = [regionIds.provinceId, regionIds.cityId, regionIds.districtId].filter(Boolean)
    } else {
      form.value.regionIds = []
    }
    
    open.value = true
    title.value = "修改商户详情信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["storeDetailRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateStoreDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addStoreDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除商户详情信息编号为"' + _ids + '"的数据项？').then(function() {
    return delStoreDetail(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('core/storeDetail/export', {
    ...queryParams.value
  }, `storeDetail_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.text-content {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.5;
  word-break: break-all;
}

.detail-content {
  padding: 20px 0;
}

.detail-text {
  max-height: 100px;
  overflow-y: auto;
  line-height: 1.6;
  word-break: break-all;
  white-space: pre-wrap;
}

.license-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 12px;
}

/* 描述列表样式优化 */
:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #606266;
  background-color: #fafafa;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

/* 表格样式优化 */
:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
}

:deep(.el-table td) {
  color: #303133;
}

/* 标签样式 */
:deep(.el-tag) {
  font-weight: 500;
}

/* 图片预览样式 */
:deep(.image-preview) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}
</style>
